<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { invoke } from "@tauri-apps/api/core";
import { debug } from "@tauri-apps/plugin-log";

const route = useRoute();
const router = useRouter();

// 面包屑导航
var material_parents = ref<Material[]>([]);

// 材料接口定义
interface Material {
    id: number;
    name: string | null;
    code: string | null;
    parent_id: number;
    supplier_id: number | null;
    color_code: string | null;
    background_material: string | null;
    status: number;
    length: number | null;
    width: number | null;
    thickness: number | null;
    residual: number | null;
    price: number | null;
    unit: string | null;
    remark: string | null;
    created_by: string;
    modified_by: string;
    created_at: string;
    modified_at: string;
    is_leaf: boolean | null;
}

// API响应接口
interface ApiResponse<T> {
    status_code: number;
    error_code: number;
    message: string;
    data: T | null;
}

var materialList = ref<Material[]>([]);
var loading = ref(false);
var error = ref("");

// 获取材料列表
async function fetchMaterials(materialId: number = 0) {
    loading.value = true;
    error.value = "";
    debug(`material id is : ${materialId}`);
    try {
        const response: ApiResponse<Material[]> = await invoke(
            "list_material",
            {
                material_id: materialId,
            },
        );

        if (response.status_code === 200 && response.data) {
            materialList.value = response.data;
        } else {
            error.value = response.message || "获取材料列表失败";
            materialList.value = [];
        }
    } catch (err) {
        error.value = "网络请求失败";
        console.error("获取材料列表失败:", err);
        materialList.value = [];
    } finally {
        loading.value = false;
    }
}

// 打开子材料或详情
async function openChildMaterial(material: Material) {
    // 检查是否有子材料
    // 如果 is_leaf 为 null，当作非叶子节点处理
    if (material.is_leaf === true) {
        // 是叶子节点，跳转到详情页面
        router.push("/materialdetail/" + material.id);
    } else {
        // 非叶子节点（包括 is_leaf 为 false 或 null），更新面包屑导航并显示子材料列表
        material_parents.value.push(material);
        await fetchMaterials(material.id);
    }
}

// 返回父级材料
async function backParentMaterial(index: number) {
    material_parents.value = material_parents.value.slice(0, index);

    if (index === 0) {
        // 返回顶级材料
        await fetchMaterials(0);
    } else {
        // 返回指定父级材料
        const parentMaterial = material_parents.value[index - 1];
        await fetchMaterials(parentMaterial.id);
    }
}

// 创建新材料
function createMaterial() {
    let parentId = 0;

    // 如果有当前父级材料，使用当前父级ID
    if (material_parents.value.length > 0) {
        const currentParent =
            material_parents.value[material_parents.value.length - 1];
        parentId = currentParent.id;
    }

    // 跳转到创建页面，传递父级ID
    router.push(`/material/create?parent_id=${parentId}`);
}

// 页面加载时初始化
onMounted(async () => {
    console.log(route.params.id);
    let material_id = 0;

    // 如果有路由参数，使用参数中的父级ID
    if (route.params.id != undefined) {
        material_id = parseInt(route.params.id as string);
        if (isNaN(material_id)) {
            material_id = 0;
        }

        // 如果有路由参数，需要获取父级链信息来构建面包屑
        // 这里需要调用API获取父级材料信息，暂时简化处理
        material_parents.value = [];
    } else {
        // 根节点，清空面包屑导航
        material_parents.value = [];
    }

    // 调用API获取材料列表
    await fetchMaterials(material_id);
});
</script>

<template>
    <main class="container">
        <div class="breadcrumbs text-sm">
            <ul>
                <li><a @click="backParentMaterial(0)">根目录</a></li>
                <li v-for="(item, index) in material_parents" :key="index">
                    <a @click="backParentMaterial(index + 1)">{{
                        item.name || "未命名"
                    }}</a>
                </li>
            </ul>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="text-center p-4">
            <span class="loading loading-spinner loading-lg"></span>
            <p>加载中...</p>
        </div>

        <!-- 错误信息 -->
        <div v-else-if="error" class="alert alert-error m-4">
            {{ error }}
        </div>

        <!-- 材料列表 -->
        <div
            v-else
            class="grid sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 w-screen"
        >
            <div
                v-for="(material, index) in materialList"
                :key="index"
                class="card bg-base-100 shadow-sm m-2.5 p-2 cursor-pointer hover:shadow-md transition-shadow"
                @click="openChildMaterial(material)"
            >
                <div class="card-body">
                    <h2 class="card-title">
                        {{ material.name || "未命名材料" }}
                    </h2>
                    <p>
                        <span v-if="material.code"
                            >编码: {{ material.code }}</span
                        ><br />
                        <span v-if="material.remark"
                            >备注: {{ material.remark }}</span
                        ><br />
                        <span class="text-sm text-gray-500">
                            {{
                                material.is_leaf === true
                                    ? "叶子节点"
                                    : material.is_leaf === false
                                      ? "目录节点"
                                      : "目录节点(null)"
                            }}
                        </span>
                    </p>
                </div>
                <figure>
                    <img
                        src="../assets/images/material-pg.png"
                        alt="材料图片"
                        class="rounded-xl"
                    />
                </figure>
            </div>

            <!-- 添加新材料按钮 -->
            <div
                class="card bg-base-100 shadow-sm m-2.5 cursor-pointer hover:shadow-md transition-shadow"
            >
                <div
                    class="card-body flex items-center justify-center h-full"
                    @click="createMaterial"
                >
                    <svg
                        class="w-12 h-12 text-gray-400 hover:text-gray-600"
                        aria-hidden="true"
                        xmlns="http://www.w3.org/2000/svg"
                        fill="none"
                        viewBox="0 0 24 24"
                    >
                        <path
                            stroke="currentColor"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M5 12h14m-7 7V5"
                        />
                    </svg>
                    <p class="text-gray-500 mt-2">添加新材料</p>
                </div>
            </div>
        </div>

        <!-- 空状态 -->
        <div
            v-if="!loading && !error && materialList.length === 0"
            class="text-center p-8"
        >
            <p class="text-gray-500">暂无材料数据</p>
            <button class="btn btn-primary mt-4" @click="createMaterial">
                创建第一个材料
            </button>
        </div>
    </main>
</template>
